package com.dcivision.lucene.extractor;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;

public class PDFBoxPDFHandler implements DocumentHandler {
  
  private static final Log log = LogFactory.getLog(PDFBoxPDFHandler.class);
  
  public PDFBoxPDFHandler() {
  }

  public String getDocumentFullText(InputStream is) throws ApplicationException {
    if (is==null) {
      return null;
    }
    
    String docText = null;
    PDDocument pddDoc = null;
    try {
      PDFParser parser = new PDFParser(is);
      parser.parse();
      pddDoc = new PDDocument(parser.getDocument());
      PDFTextStripper stripper = new PDFTextStripper();
      docText = stripper.getText(pddDoc);
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.INDEX_UNEXPECTED_EXCEPTION, e, e.toString());
    } finally {
      try {pddDoc.close();}catch (Exception ex) {}
    }
    return docText;
  }
  
  public static void main(String[] args) throws Exception {
    PDFBoxPDFHandler handler = new PDFBoxPDFHandler();
    String fullText = handler.getDocumentFullText(new FileInputStream(new File(args[0])));
    System.out.println(fullText);
  }
}
